package com.ylyl.langchain4j14chatmcp.controller;


import com.google.errorprone.annotations.Var;
import com.ylyl.langchain4j14chatmcp.service.McpService;
import dev.langchain4j.mcp.McpToolProvider;
import dev.langchain4j.mcp.client.DefaultMcpClient;
import dev.langchain4j.mcp.client.McpClient;
import dev.langchain4j.mcp.client.transport.stdio.StdioMcpTransport;
import dev.langchain4j.model.chat.StreamingChatModel;
import dev.langchain4j.service.AiServices;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.Map;

@RestController
public class McpCallServerController {

    @Resource
    private StreamingChatModel streamingChatModel;

    @GetMapping("/mcp/chat")
    public Flux<String> chat(@RequestParam("question") String question){

        StdioMcpTransport transport = new StdioMcpTransport.Builder()
                .command(List.of("cmd", "/c", "npx", "-y", "@amap/amap-maps-mcp-server"))
                .environment(Map.of("AMAP_MAPS_API_KEY", System.getenv("AMAP_MAPS_API_KEY")))
                .build();

        //构建McpClient客户端
        McpClient mcpClient = new DefaultMcpClient.Builder()
                .transport(transport)
                        .build();

        //创建工具集和原生的FunctionCalling
        McpToolProvider toolProvider = McpToolProvider.builder()
                .mcpClients(mcpClient)
                .build();

        //通过Aiservices给我们自定义的接口McpService构建实现并将工具集和大模型赋值给Aiservice

        McpService mcpService = AiServices.builder(McpService.class)
                .streamingChatModel(streamingChatModel)
                .toolProvider(toolProvider)
                .build();

        //调用我们自定义的HighApi接口，通过大模型对高德的调用
        return mcpService.chat(question);
    }
}
